package com.example.carbonbackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.carbonbackend.common.BaseResponse;
import com.example.carbonbackend.common.ErrorCode;
import com.example.carbonbackend.common.ResultUtils;
import com.example.carbonbackend.exception.BusinessException;
import com.example.carbonbackend.exception.ThrowUtils;
import com.example.carbonbackend.model.dto.ListingInfo.ListingInfoAddRequest;
import com.example.carbonbackend.model.dto.ListingInfo.ListingInfoQueryRequest;
import com.example.carbonbackend.model.dto.ListingInfo.ListingInfoUpdateRequest;
import com.example.carbonbackend.model.entity.CompanyUser;
import com.example.carbonbackend.model.entity.ListingInfo;
import com.example.carbonbackend.model.entity.User;
import com.example.carbonbackend.model.vo.ListingInfoVO;
import com.example.carbonbackend.service.CompanyUserService;
import com.example.carbonbackend.service.ListingInfoService;
import com.example.carbonbackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Slf4j
@RestController
@RequestMapping("listingInfo")
public class ListingInfoController {


    @Resource
    UserService userService;
    @Resource
    ListingInfoService listingInfoService;
    @Resource
    CompanyUserService companyUserService;

    @PostMapping("add")
    public BaseResponse<Long> AddListing(@RequestBody ListingInfoAddRequest listing, HttpServletRequest request) {

        if (listing == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        ListingInfo listingInfo = new ListingInfo();
        // 根据userid查询companyId
        User loginUser = userService.getLoginUser(request);
        QueryWrapper<CompanyUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", loginUser.getId());
        CompanyUser companyUser = companyUserService.getOne(queryWrapper);

        BeanUtils.copyProperties(listing, listingInfo);
        // 设置属性
        listingInfo.setCompanyId(String.valueOf(companyUser.getCompanyId()));
        listingInfo.setResidualAmount(listing.getListingAmount());
        listingInfo.setMaxPrice(listing.getListingPrice());
        listingInfo.setMinPrice(listing.getListingPrice());
        listingInfo.setEndTime(new Date());
        boolean save = listingInfoService.save(listingInfo);
        if (!save) {

            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }

        return ResultUtils.success(Long.valueOf(listingInfo.getCompanyId()));
    }


    @PostMapping("deleteById")
    public BaseResponse<Boolean> deleteById(@RequestBody ListingInfoUpdateRequest listingInfoUpdateRequest, HttpServletRequest request)
    {
        UpdateWrapper<ListingInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",listingInfoUpdateRequest.getId());

        updateWrapper.set("is_delete",listingInfoUpdateRequest.getIsDelete());
        boolean update = listingInfoService.update(updateWrapper);
        return ResultUtils.success(update);
    }
    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<ListingInfoVO> getListingInfoVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        ListingInfo listingInfo = listingInfoService.getById(id);
        if (listingInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(listingInfoService.getListingInfoVO(listingInfo, request));
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param listingInfoQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<ListingInfo>> listListingInfoByPage(@RequestBody ListingInfoQueryRequest listingInfoQueryRequest) {
        long current = listingInfoQueryRequest.getCurrent();
        long size = listingInfoQueryRequest.getPageSize();
        Page<ListingInfo> listingInfoPage = listingInfoService.page(new Page<>(current, size),
                listingInfoService.getQueryWrapper(listingInfoQueryRequest));
        return ResultUtils.success(listingInfoPage);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param listingInfoQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<ListingInfoVO>> listListingInfoVOByPage(@RequestBody ListingInfoQueryRequest listingInfoQueryRequest,
                                                                     HttpServletRequest request) {
        long current = listingInfoQueryRequest.getCurrent();
        long size = listingInfoQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<ListingInfo> listingInfoPage = listingInfoService.page(new Page<>(current, size),
                listingInfoService.getQueryWrapper(listingInfoQueryRequest));
        return ResultUtils.success(listingInfoService.getListingInfoVOPage(listingInfoPage, request));
    }

    /**
     * 分页获取当前用户的公司的挂牌列表
     *
     * @param listingInfoQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<ListingInfoVO>> listMyListingInfoVOByPage(@RequestBody ListingInfoQueryRequest listingInfoQueryRequest,
                                                                       HttpServletRequest request) {

        if (listingInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        QueryWrapper<CompanyUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", loginUser.getId());
        CompanyUser companyUser = companyUserService.getOne(queryWrapper);
        listingInfoQueryRequest.setCompanyId(String.valueOf(companyUser.getCompanyId()));

        long current = listingInfoQueryRequest.getCurrent();
        long size = listingInfoQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<ListingInfo> listingInfoPage = listingInfoService.page(new Page<>(current, size),
                listingInfoService.getQueryWrapper(listingInfoQueryRequest));
        log.info("查询信息{}", listingInfoQueryRequest);
        log.info("查询内容：{}", listingInfoPage.getRecords());
        return ResultUtils.success(listingInfoService.getListingInfoVOPage(listingInfoPage, request));
    }
}
